import React, { Component } from 'react'
import { BrowserRouter as Router, Switch, Redirect, Route } from 'react-router-dom'
import { ConfigProvider, Spin } from 'antd'
import zh_CN from 'antd/lib/locale-provider/zh_CN'
import moment from 'moment'
import 'moment/locale/zh-cn'
import Loadable from 'react-loadable'

import getData from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'
import { ACTIVATE_STATUS, USER_INFO, PERMISSION_LIST } from '@/Utils/CONST'

import Tip from '../Utils/Tip'

moment.locale('zh-cn')

export default class App extends Component {
  constructor(props) {
    super(props)
    const activated = +(localStorage.getItem(ACTIVATE_STATUS) || '')
    this.state = {
      activated: !!activated,
      loading: !activated,
    }
  }

  componentDidMount() {
    const { loading } = this.state
    loading && this.getActivateStatus()
  }

  getActivateStatus = async() => {
    const { status, data = {}} = await getData().get(address.license.getStatus)
    this.setState({
      loading: false,
    })
    if (status === 200 && data) {
      localStorage.setItem(ACTIVATE_STATUS, data.activated ? '1' : '0')
      this.setState({
        activated: data.activated,
      })
    }
  }

  render() {
    const { activated, loading } = this.state
    return (
      <ConfigProvider
        autoInsertSpaceInButton={false}
        locale={zh_CN} >
        <Router path="/">
          <Spin size="large" spinning={loading}>
            <div className="App">
              {
                !loading &&
                <Switch>
                  {
                    activated &&
                    [
                      <PrivateRoute key="dashboard" path="/dashboard" component={Dashboard} />,
                      <Route key="register" path="/inner/register" component={Register} />,
                      <Route key="login" path="/login" component={Login} />,
                      <Route key="document" path="/document" component={Document} />,
                      <Route key="error" path="/error/:code" component={ErrorPage} />,
                      <Route key="all-login" path="/*" render={() => <Redirect to="/login" />} />,
                    ]
                  }
                  {
                    !activated &&
                    [
                      <Route key="activate" path="/activate" component={Activate} />,
                      <Route key="all-activate" path="/*" render={() => <Redirect to="/activate" />} />,
                    ]
                  }
                </Switch>
              }
            </div>
          </Spin>
        </Router>
      </ConfigProvider>
    )
  }
}

class PrivateRoute extends Component {
  constructor(props) {
    super(props)
    this.state = {
      userInfo: {},
      loading: true,
    }
  }

  componentDidMount() {
    this.getUserInfo()
  }

  getUserInfo = async() => {
    const { status, data = {}} = await getData().get(address.user.info)
    if (status === 200) {
      const userInfo = data || {}
      localStorage.setItem(USER_INFO, JSON.stringify(userInfo))
      await this.getRolePermission(userInfo.role) // 获取权限
      this.setState({
        userInfo,
      })
    }
    this.setState({
      loading: false,
    })
  }

  getResourceList = async() => {
    const { status, data = {}} = await getData().get(address.resource.getList)
    if (status === 200) {
      return (data.data || []).map(v => {
        return {
          ...v,
          id: v.id,
          name: v.name,
          parentId: v.parent_id,
        }
      })
    }
  }

  // 获取角色所管理的权限
  getRolePermission = async(roleId) => {
    const resourceList = await this.getResourceList() // 获取收益资源列表
    if (resourceList && resourceList.length === 0) {
      return localStorage.setItem(PERMISSION_LIST, [])
    }
    // 获取角色权限列表
    const { status, data = {}} = await getData().get(address.permission.create, {
      params: {
        roleId,
      },
    })
    if (status === 200) {
      const permissions = (data.data || []).map(v => v.resource_id) // 角色所拥有的资源id
      const perList = resourceList.filter(v => permissions.includes(v.id)).map(v => {
        return {
          type: v.type,
          name: v.name,
          id: v.id,
          resource_url: v.resource_url,
          method: v.method,
        }
      })
      localStorage.setItem(PERMISSION_LIST, JSON.stringify(perList)) // 存储权限
    }
  }

  render() {
    const { component: Component, ...rest } = this.props
    const { loading, userInfo } = this.state
    const auth = userInfo && userInfo.auth
    return (
      <Spin size="large" spinning={loading}>
        <div style={{ width: '100%', minHeight: '100vh' }}>
          {
            !loading &&
            <Route {...rest} render={props => {
              if (userInfo && userInfo.id) {
                if (auth && auth.isPaused) {
                  return <Redirect to={{ pathname: '/error/isPaused', state: { from: props.location }}} />
                }
                return auth && auth !== 'ignore'
                  ? auth.isCustomer ? (
                    auth.isCertificated ? (
                      auth.isAuthorised
                        ? <Route {...rest} render={props => <Component {...props} />} />
                        : <Redirect to={{ pathname: '/error/no-authority', state: { from: props.location }}} />)
                      : <Redirect to={{ pathname: '/error/no-certified', state: { from: props.location }}} />)
                    : <Redirect to={{ pathname: '/error/403', state: { from: props.location }}} />
                  : <Route {...rest} render={props => <Component {...props} />} />
              }
              return <Redirect to="/login" />
            }} />
          }
        </div>
      </Spin>

    )
  }
}

const MyLoadingComponent = ({ isLoading, error }) => {
  if (isLoading) {
    return (
      <div />
    )
  } else if (error) {
    return <Tip />
  } else {
    return null
  }
}

const ErrorPage = Loadable({
  loader: () => import('../pages/Dashboard/components/Error'),
  loading: MyLoadingComponent,
})

const Dashboard = Loadable({
  loader: () => import('../pages/Dashboard/basicLayout'),
  loading: MyLoadingComponent,
})

const Login = Loadable({
  loader: () => import('../pages/Login/login'),
  loading: MyLoadingComponent,
})

const Register = Loadable({
  loader: () => import('../pages/Register'),
  loading: MyLoadingComponent,
})

const Activate = Loadable({
  loader: () => import('../pages/Activate'),
  loading: MyLoadingComponent,
})

const Document = Loadable({
  loader: () => import('../pages/Dashboard/components/LeagueInfo/components/Chaincode/ChaincodeDocument'),
  loading: MyLoadingComponent,
})
